package com.yzt.message.serviceimpl;

import android.content.Context;
import android.net.Uri;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.yzt.zhuju.IService.chatroom.ChatRoomMsgType;
import com.yzt.zhuju.IService.message.IChatRoomMessageService;
import com.yzt.zhuju.IService.message.MessageCallback;
import com.yzt.zhuju.manager.RongYunOnReceiverMsgManager;
import com.yzt.zhuju.network.entity.chatroom.ChatRoomChatMessage;
import com.yzt.zhuju.rongyun.ChatRoomMessage;
import com.yzt.p_base.AppUtils;
import com.yzt.p_base.utils.ThreadCenter;
import com.yzt.message.IMManager;

import io.rong.imlib.IRongCallback.ISendMessageCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.RongIMClient.ErrorCode;
import io.rong.imlib.RongIMClient.OperationCallback;
import io.rong.imlib.RongIMClient.ResultCallback;
import io.rong.imlib.RongIMClient.SendImageMessageCallback;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.ImageMessage;
import io.rong.message.TextMessage;

import java.util.List;

/**
 * @author zhly
 * created on: 2022/7/26 14:27
 * description:
 */
@Route(path = "/message/chatRoomMessageService")
public class ChatRoomMessageServiceImpl implements IChatRoomMessageService {

    @Override
    public void init(Context context) {

    }

    @Override
    public void joinChatRoom(String chatRoomId, int defMessageCount, JoinChatRoomCallback callback) {
        RongIMClient.getInstance().joinChatRoom(chatRoomId, defMessageCount, new OperationCallback() {
            @Override
            public void onSuccess() {
                if (callback != null) {
                    callback.onSuccess();
                }
            }

            @Override
            public void onError(ErrorCode errorCode) {
                if (callback != null) {
                    if (errorCode.getValue() == RongIMClient.ErrorCode.KICKED_FROM_CHATROOM.getValue()) {
                        callback.onBeKicked();
                    } else {
                        callback.onError(errorCode.code, errorCode.msg);
                    }
                }
            }
        });
    }

    @Override
    public void quitChatRoom(String chatRoomId, MessageCallback callback) {
        RongIMClient.getInstance().quitChatRoom(chatRoomId, new OperationCallback() {
            @Override
            public void onSuccess() {
                if (callback != null) {
                    callback.onSuccess();
                }
            }

            @Override
            public void onError(ErrorCode errorCode) {
                if (callback != null) {
                    callback.onError(errorCode.code, errorCode.msg);
                }
            }
        });
    }

    @Override
    public void sendChatRoomTextMessage(String chatRoomId, String messageContent, ChatRoomChatMessage chatMessageInfo,
                                        MessageCallback callback) {
        Conversation.ConversationType conversationType = Conversation.ConversationType.CHATROOM;
        TextMessage textMessage = TextMessage.obtain(messageContent);
        if (chatMessageInfo != null) {
            textMessage.setExtra(JSON.toJSONString(chatMessageInfo));
        }
        Message message = Message.obtain(chatRoomId, conversationType, textMessage);
        RongIMClient.getInstance().sendMessage(message, null, null, new ISendMessageCallback() {
            @Override
            public void onAttached(Message message) {
            }

            @Override
            public void onSuccess(Message message) {
                //消息发送成功后做本地分发
                TextMessage arrivedTextMessage = (TextMessage) (message.getContent());
                RongYunOnReceiverMsgManager
                        .getInstance().spreadChatRoomMessageNotAddToCache(new ChatRoomMessage(ChatRoomMsgType.TYPE_SIMPLE_TEXT,
                        message.getMessageId(), arrivedTextMessage.getContent(), arrivedTextMessage.getExtra(), -1, message.getTargetId()));
                if (callback != null) {
                    callback.onSuccess();
                }
            }

            @Override
            public void onError(Message message, ErrorCode errorCode) {
                if (callback != null) {
                    callback.onError(errorCode.code, errorCode.msg);
                }
            }
        });
    }

    @Override
    public void sendChatRoomImageMessage(String chatRoomId, String imagePath, ChatRoomChatMessage chatMessageInfo, MessageCallback callback) {
        if (!imagePath.startsWith("file://")) {
            imagePath = "file://" + imagePath;
        }
        Uri localUri = Uri.parse(imagePath);

        Conversation.ConversationType conversationType = Conversation.ConversationType.CHATROOM;
        ImageMessage imageMessage = ImageMessage.obtain(null, localUri);
        imageMessage.setExtra(JSON.toJSONString(chatMessageInfo));
        RongIMClient.getInstance().sendImageMessage(conversationType, chatRoomId, imageMessage, null, null,
                new SendImageMessageCallback() {
                    @Override
                    public void onAttached(Message message) {

                    }

                    @Override
                    public void onError(Message message, ErrorCode errorCode) {
                        if (callback != null) {
                            callback.onError(errorCode.code, errorCode.msg);
                        }
                    }

                    @Override
                    public void onSuccess(Message message) {
                        ImageMessage arrivedImageMessage = (ImageMessage) (message.getContent());
                        RongYunOnReceiverMsgManager.getInstance().spreadChatRoomMessageNotAddToCache(
                                new ChatRoomMessage(ChatRoomMsgType.TYPE_PHOTO, message.getMessageId(),
                                        arrivedImageMessage.getRemoteUri().toString(), arrivedImageMessage.getExtra(), -1, message.getTargetId()));
                        if (callback != null) {
                            callback.onSuccess();
                        }
                    }

                    @Override
                    public void onProgress(Message message, int i) {
                    }
                });
    }

    @Override
    public void getChatRoomHistoryMessages(String chatRoomId, int count, MessageCallback callback) {
        RongIMClient.getInstance().getHistoryMessages(Conversation.ConversationType.CHATROOM, chatRoomId, -1, count,
                new ResultCallback<List<Message>>() {
                    @Override
                    public void onSuccess(List<Message> messages) {
                        ThreadCenter.postNormalThread(() -> {
                            for (int i = messages.size() - 1; i >= 0; i--) {
                                Message message = messages.get(i);
                                IMManager.doReceivedMsg(message, AppUtils.getApp(), true);
                            }
                        });
                        if (callback != null) {
                            callback.onSuccess();
                        }
                    }

                    @Override
                    public void onError(ErrorCode errorCode) {
                        if (callback != null) {
                            callback.onError(errorCode.code, errorCode.msg);
                        }
                    }
                });
    }
}
